//
//  ChatMessageMgr.m
//  WxSdk
//
//  Created by fusuwei on 14-9-11.
//  Copyright (c) 2014年 网信金融集团. All rights reserved.
//

#import "ChatMessageMgr.h"
#include "PublicMacros.h"
#include "EPublicMacros.h"
#import "UcfgroupXMPPManger.h"
#import "ChatRecent.h"
#import "Utility.h"
#import "GetChatMessage.h"
#import "ChatMessage.h"

static BOOL initReadOnce = YES;


@implementation ChatMessageMgr


+(NSString *)getDbPathName
{
    NSString *userId = [UcfgroupXMPPManger sharedInstance].logRegWxUserObject.UserId;
    if (initReadOnce && (userId == nil)) {
        initReadOnce = NO;
        userId = [[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_ID];
    }
    NSString *fileName = [Utility truncateNSString:userId To:kXMPPmyDomain];
    NSString *isFilePathName = [NSString stringWithFormat:@"%@/%@",DATABASE_PATH,fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:isFilePathName]) {
        [fileManager createDirectoryAtPath:isFilePathName withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *filePathName = [NSString stringWithFormat:@"%@/%@%@",DATABASE_PATH,fileName,@"/wxChatIM.db"];
    return filePathName;
}


//查找收到的与某一好友聊天的 未读消息数量  toId---对方好友Id
+ (NSInteger)findUnreadMsgNumberby:(NSString *)toId
{
    NSInteger retVal = 0;
    
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据打开失败");
        return 0;
    }
    
    NSString *queryString=@"select count(*) from ChatMessage where contactId=? and status=?";
    YY_FMResultSet *rs=[db executeQuery:queryString,toId,@"NO"]; //@"NO"处填未读状态值
    while ([rs next])
    {
        int count= [rs intForColumnIndex:0];
        if (count!=0){
            retVal = count;
            break;
        }
        else
        {
            break;
        }
    }
    [rs close];
    
    return retVal;
}


//check ChatMessage table is create in db
+(BOOL)checkChatMessageTableCreatedInDb:(YY_FMDatabase *)db
{
    BOOL worked = NO;
    NSString *createTable=@"CREATE  TABLE  IF NOT EXISTS ChatMessage ('messageId' VARCHAR NOT NULL UNIQUE, 'messageType' INT default 1, 'messageBody' VARCHAR, 'createTime' VARCHAR, 'messageStatus' INT default 0, 'contactId' VARCHAR, 'contactName' VARCHAR,'isIncoming' INT, 'isGroupMsg' INT default 0, 'isRead' INT default 0 , 'duration' INT  default 0, 'content' VARCHAR, 'thumbnail' VARCHAR, 'localFileUrl' VARCHAR, 'serverFileName' VARCHAR, 'fileSize' INT default 0, 'fileName' VARCHAR,'fromMemID' VARCHAR, 'isTop' INT default 0)";
    worked = [db executeUpdate:createTable];
    if (!worked) {
        WXLog(@"Create ChatMessage'table resutl %d fail",worked);
    }
    
    FMDBQuickCheck(worked);
    return worked;
}

//查找messageId是否存在
+(BOOL)isFindTheMessageIdExist:(NSString*)messageId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return YES;
    };
    
    [self checkChatMessageTableCreatedInDb:db];
    
    YY_FMResultSet *rs = [db executeQuery:@"select count(*) from ChatMessage where messageId=?",messageId];
    
    while ([rs next]) {
        int count= [rs intForColumnIndex:0];
        
        if (count!=0){
            [rs close];
            return YES;
        }else
        {
            [rs close];
            return NO;
        }
    };
    [rs close];
    return YES;
}

//保存消息对象 MessageBase 到ChatMessage表
+(BOOL)saveChatMessageObj:(MessageBase *)chatMessage
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    [self checkChatMessageTableCreatedInDb:db];
    
    //如果在表中已经存在，就更新此条消息的creatTime
    if([self isFindTheMessageIdExist:chatMessage.messageId])
    {
        BOOL retb = [self updateMessageId:chatMessage.messageId withObj:chatMessage];
        return retb;
    }

    NSInteger istop = [self checkIsTopState:chatMessage.contactId] ? 1 : 0;
    //否则插入此条消息
    NSString *insertStr = @"INSERT INTO ChatMessage ('messageId','messageType','messageBody','createTime','messageStatus','contactId','contactName','isIncoming','isGroupMsg','isRead','duration','content','thumbnail','localFileUrl','serverFileName', 'fileSize', 'fileName','fromMemID','isTop') VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    
    BOOL worked = [db executeUpdate:insertStr,chatMessage.messageId,
                   [NSNumber numberWithInteger:chatMessage.messageType],
                   chatMessage.messageBody,
                   chatMessage.createTime,
                   [NSNumber numberWithInt:chatMessage.messageStatus],
                   chatMessage.contactId,
                   chatMessage.contactName,
                   [NSNumber numberWithInt:chatMessage.isIncoming],
                   [NSNumber numberWithInt:chatMessage.isGroupMsg],
                   [NSNumber numberWithInt:chatMessage.isRead],
                   [NSNumber numberWithInteger:chatMessage.duration],
                   chatMessage.content,
                   chatMessage.thumbnail,
                   chatMessage.localFileUrl,
                   chatMessage.serverFileName,
                   [NSNumber numberWithInteger:chatMessage.fileSize],
                   chatMessage.fileName,
                   chatMessage.frommemberID,
                   [NSNumber numberWithInteger:istop]];
    [db close];
    
    WXLog(@"保存消息成功！！！！！")
    
    //add by wjy begin......为方便集成sdk用户，能够拿到一些基本的新消息内容并使用。
    ChatMessage *message = [[ChatMessage alloc] init];
    message.messageId = chatMessage.messageId;
    message.messageType = chatMessage.messageType;
    message.createTime = chatMessage.createTime;
    message.messageStatus = chatMessage.messageStatus;
    message.contactId = chatMessage.contactId;
    message.isIncoming = chatMessage.isIncoming;
    message.isGroupMsg = chatMessage.isGroupMsg;
    message.isRead = chatMessage.isRead;
    message.messageBody = chatMessage.messageBody;
    message.fromMemberID = chatMessage.frommemberID;
    //end.....
    
    
    //发送收到新聊天消息通知
    [[NSNotificationCenter defaultCenter] postNotificationName:kXMPPRecvChatMsgNotifaction object:message];
    
    return worked;
}
+(BOOL)saveChatMessageObjOnly:(MessageBase *)chatMessage{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    [self checkChatMessageTableCreatedInDb:db];
    
    //如果在表中已经存在，就更新此条消息的creatTime
    if([self isFindTheMessageIdExist:chatMessage.messageId])
    {
        BOOL retb = [self updateMessageId:chatMessage.messageId withObj:chatMessage];
        return retb;
    }
    
    NSInteger istop = [self checkIsTopState:chatMessage.contactId] ? 1 : 0;
    //否则插入此条消息
    NSString *insertStr = @"INSERT INTO ChatMessage ('messageId','messageType','messageBody','createTime','messageStatus','contactId','contactName','isIncoming','isGroupMsg','isRead','duration','content','thumbnail','localFileUrl','serverFileName', 'fileSize', 'fileName','fromMemID','isTop') VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    
    BOOL worked = [db executeUpdate:insertStr,chatMessage.messageId,
                   [NSNumber numberWithInteger:chatMessage.messageType],
                   chatMessage.messageBody,
                   chatMessage.createTime,
                   [NSNumber numberWithInt:chatMessage.messageStatus],
                   chatMessage.contactId,
                   chatMessage.contactName,
                   [NSNumber numberWithInt:chatMessage.isIncoming],
                   [NSNumber numberWithInt:chatMessage.isGroupMsg],
                   [NSNumber numberWithInt:chatMessage.isRead],
                   [NSNumber numberWithInteger:chatMessage.duration],
                   chatMessage.content,
                   chatMessage.thumbnail,
                   chatMessage.localFileUrl,
                   chatMessage.serverFileName,
                   [NSNumber numberWithInteger:chatMessage.fileSize],
                   chatMessage.fileName,
                   chatMessage.frommemberID,
                   [NSNumber numberWithInteger:istop]];
    [db close];
    
    WXLog(@"保存消息成功！！！！！")
    
    //add by wjy begin......为方便集成sdk用户，能够拿到一些基本的新消息内容并使用。
    ChatMessage *message = [[ChatMessage alloc] init];
    message.messageId = chatMessage.messageId;
    message.messageType = chatMessage.messageType;
    message.createTime = chatMessage.createTime;
    message.messageStatus = chatMessage.messageStatus;
    message.contactId = chatMessage.contactId;
    message.isIncoming = chatMessage.isIncoming;
    message.isGroupMsg = chatMessage.isGroupMsg;
    message.isRead = chatMessage.isRead;
    message.messageBody = chatMessage.messageBody;
    message.fromMemberID = chatMessage.frommemberID;
    //end.....    
    return worked;
}
//读取某个消息对象  到MessageBase对象中
+(MessageBase *)readChatMessageObjByMsgId:(NSString *)msgId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return nil;
    };
    [self checkChatMessageTableCreatedInDb:db];
    
    MessageBase *message = nil;
    
    NSString *findStr = [NSString stringWithFormat:@"select * from ChatMessage where messageId=?"];

    YY_FMResultSet *rs=[db executeQuery:findStr,msgId];
    while ([rs next]) {
                message = [[MessageBase alloc] init];
                message.messageId = [rs stringForColumn:@"messageId"];
                message.messageBody = [rs stringForColumn:@"messageBody"];
                message.messageType = (NSUInteger)[rs intForColumn:@"messageType"];
                message.createTime = [rs stringForColumn:@"createTime"];
        
                message.messageStatus = (ChatMsgState)[rs intForColumn:@"messageStatus"];
                message.isIncoming = (MsgIOStateType)[rs intForColumn:@"isIncoming"];
                message.contactId = [rs stringForColumn:@"contactId"];
                message.contactName = [rs stringForColumn:@"contactName"];
                message.isGroupMsg = [rs intForColumn:@"isGroupMsg"];
        
                message.isRead = [rs intForColumn:@"isRead"];
                message.duration = [rs intForColumn:@"duration"];
                message.content = [rs stringForColumn:@"content"];
                message.thumbnail = [rs stringForColumn:@"thumbnail"];
        
                message.localFileUrl = [rs stringForColumn:@"localFileUrl"];
                message.serverFileName = [rs stringForColumn:@"serverFileName"];
        
                message.fileSize = [rs intForColumn:@"fileSize"];
                message.fileName = [rs stringForColumn:@"fileName"];
                message.frommemberID = [rs stringForColumn:@"fromMemID"];
    }
    
    return message;
}

//更新指定NSString字段
+(BOOL)saveUpdateMessageId:(NSString*)messageId fieldName:(NSString*)fieldName value:(NSString*)value
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *updateStr = [NSString stringWithFormat:@"update ChatMessage set %@=? where messageId=?",fieldName];
    
    BOOL worked = [db executeUpdate:updateStr,value, messageId];
    
    [db close];
    
    
    return worked;
}


//更新指定NSInteger字段
+(BOOL)saveUpdateMessageId:(NSString*)messageId fieldName:(NSString*)fieldName valueInt:(NSInteger)value
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *updateStr = [NSString stringWithFormat:@"update ChatMessage set %@=? where messageId=?",fieldName];
    
    BOOL worked = [db executeUpdate:updateStr,[NSNumber numberWithInteger:value], messageId];
    
    //FMDBQuickCheck(worked);
    
    [db close];
    
    return worked;
}

//更新消息
+(BOOL)updateMessageId:(NSString*)messageId withObj:(MessageBase *)chatMessage
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *updateStr = @"update ChatMessage set messageType=?, messageBody=?, createTime=?, messageStatus=?, contactId=?, contactName=?, isIncoming=?, isGroupMsg=?, isRead=?, duration=?,content=?, thumbnail=?,localFileUrl=?, serverFileName=?, fileSize=?, fileName=? where  messageId=?";
    
    BOOL worked = [db executeUpdate:updateStr,
                   [NSNumber numberWithInteger:chatMessage.messageType],
                   chatMessage.messageBody,
                   chatMessage.createTime,
                   [NSNumber numberWithInt:chatMessage.messageStatus],
                   chatMessage.contactId,
                   chatMessage.contactName,
                   [NSNumber numberWithInt:chatMessage.isIncoming],
                   [NSNumber numberWithInt:chatMessage.isGroupMsg],
                   [NSNumber numberWithInt:chatMessage.isRead],
                   [NSNumber numberWithInteger:chatMessage.duration],
                   chatMessage.content,
                   chatMessage.thumbnail,
                   chatMessage.localFileUrl,
                   chatMessage.serverFileName,
                   [NSNumber numberWithInteger:chatMessage.fileSize],
                   chatMessage.fileName,
                   chatMessage.messageId];
    [db close];
    
    return worked;
}

//获取某联系人聊天记录
+(NSMutableArray*)fetchMessageListWithUser:(NSString *)userId beginIndex:(NSInteger)beginIndex count:(NSInteger)count
{
    NSMutableArray *messageList = [[NSMutableArray alloc] init];
    
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据打开失败");
        return messageList;
    }
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *queryString = nil;
    YY_FMResultSet *rs = nil;
    
    if (count == 0) {
        queryString = @"select * from ChatMessage where contactId=? order by createTime desc";//order by createTime desc
        rs = [db executeQuery:queryString,userId];
    }
    else
    {
        queryString = @"select * from ChatMessage where contactId=? limit ?,? order by createTime desc";//order by createTime desc
        rs = [db executeQuery:queryString,userId ,[NSNumber numberWithInteger:beginIndex],[NSNumber numberWithInteger:count]];
    }
    
    while ([rs next]) {
        //创建ChatMessage对象并保存到数据库表
        MessageBase *message = [[MessageBase alloc] init];
        message.messageId = [rs stringForColumn:@"messageId"];
        message.messageBody = [rs stringForColumn:@"messageBody"];
        message.messageType = (NSUInteger)[rs intForColumn:@"messageType"];
        message.createTime = [rs stringForColumn:@"createTime"];
        
        message.messageStatus = (ChatMsgState)[rs intForColumn:@"messageStatus"];
        message.isIncoming = (MsgIOStateType)[rs intForColumn:@"isIncoming"];
        message.contactId = [rs stringForColumn:@"contactId"];
        message.contactName = [rs stringForColumn:@"contactName"];
        message.isGroupMsg = [rs intForColumn:@"isGroupMsg"];
        
        message.isRead = [rs intForColumn:@"isRead"];
        message.duration = [rs intForColumn:@"duration"];
        message.content = [rs stringForColumn:@"content"];
        message.thumbnail = [rs stringForColumn:@"thumbnail"];
        
        message.localFileUrl = [rs stringForColumn:@"localFileUrl"];
        message.serverFileName = [rs stringForColumn:@"serverFileName"];
        
        message.fileSize = [rs intForColumn:@"fileSize"];
        message.fileName = [rs stringForColumn:@"fileName"];
        message.frommemberID = [rs stringForColumn:@"fromMemID"];

        
        id messageObj = [[UcfgroupXMPPManger sharedInstance] distributeMsgType:message.messageType message:message];

        GetChatMessage *dispathObj = [[GetChatMessage alloc] init];
        dispathObj.messageType = message.messageType;
        dispathObj.message = messageObj;

        [messageList addObject:dispathObj];
    }
    
    
    
    
    
    
    //messageList = (NSMutableArray *)[[messageList reverseObjectEnumerator] allObjects];
    
    return  messageList;
}

//检查聊天记录中未正常发出的状态
+ (BOOL)checkMessageListAllState
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据打开失败");
        return NO;
    }
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *queryString = @"select messageId, messageStatus from ChatMessage where messageStatus= ?";
    YY_FMResultSet *rs = rs = [db executeQuery:queryString,[NSNumber numberWithInteger:Chat_Send_Sending]];
    
    //创建ChatMessage对象并保存到数据库表
    MessageBase *message = [[MessageBase alloc] init];
    
    while ([rs next]) {
        message.messageId = [rs stringForColumn:@"messageId"];
        message.messageStatus = (ChatMsgState)[rs intForColumn:@"messageStatus"];
        
        message.messageStatus = Chat_Send_Failure;
        
        NSString *updateStr = [NSString stringWithFormat:@"update ChatMessage set messageStatus=? where messageId=?"];
        BOOL worked = [db executeUpdate:updateStr,[NSNumber numberWithInteger:message.messageStatus], message.messageId];
        if (!worked) {
            WXLog(@"更新失败！！！");
        }
    }
    
    return  YES;
}

//删除与某个联系人聊天所有记录
+(BOOL)deleteAllMessageToContactId:(NSString *)contactId
{
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"deleteAllMessageToContactId---数据打开失败");
        return NO;
    }
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *deleteStr = [NSString stringWithFormat:@"DELETE FROM ChatMessage where contactId=?"];
    
    BOOL worked = [db executeUpdate:deleteStr, contactId];
    
    return worked;
}

//获取最近聊天过的联系人最新消息记录列表
+(NSMutableArray *)fetchRecentChatByPage:(NSUInteger)pageIndex
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return nil;
    };
    [self checkChatMessageTableCreatedInDb:db];
    
    NSMutableArray *messageList=[[NSMutableArray alloc] init];
    
    NSString *queryString=@"select contactId,messageBody,max(createTime) as createTime,contactName ,isTop ,isGroupMsg ,isRead ,isIncoming from ChatMessage group by contactId order by isTop desc, createTime desc";
//    NSString *queryString = @"select * from ChatMessage group by contactId order by isTop desc, createTime desc";

    YY_FMResultSet *rs=[db executeQuery:queryString];
    while ([rs next]) {
        ChatRecent *last = [[ChatRecent alloc] init];
        last.ContactId = [rs stringForColumn:@"contactId"];
        
        last.messageBody = [rs stringForColumn:@"messageBody"];
        last.createTime = [rs stringForColumn:@"createTime"];
        last.ContactName = [rs stringForColumn:@"contactName"];
        last.isTop = [rs intForColumn:@"isTop"];
        
        BOOL isGroupMsg = [rs intForColumn:@"isGroupMsg"];
        {
            last.isGroupChat = isGroupMsg;
            
            if ([last.ContactName isEqualToString:@""]||last.ContactName == nil) {
                YY_FMResultSet *rsSub = nil;
                if (isGroupMsg)
                {
                    rsSub = [db executeQuery:@"select ChatMessage.contactId,ChatMessage.contactName,GroupList.group_id,GroupList.group_name from ChatMessage,GroupList where ChatMessage.contactId=GroupList.group_id group by GroupList.group_id"];
                    while ([rsSub next]) {
                        if ([[rsSub stringForColumn:@"group_id"] isEqualToString:last.ContactId])
                        {
                            last.ContactName = [rsSub stringForColumn:@"group_name"];
                        }
                    }
                }
                else
                {
                    NSString *contactId = nil;
                    rsSub = [db executeQuery:@"select ChatMessage.contactId,ChatMessage.contactName,ChatContact.ContactName from ChatMessage,ChatContact where ChatMessage.contactId=ChatContact.ContactId group by ChatContact.ContactId"];
                    while ([rsSub next]) {
                        contactId = [rsSub stringForColumn:@"contactId"];
                        if ([[Utility getBareContactId:contactId] isEqualToString:last.ContactId])
                        {
                            last.ContactName = [rsSub stringForColumn:@"ContactName"];
                        }
                    }
                }
                
                [rsSub close];
            }
        }
        //add by wjy 查询未读的消息数目 begin...
        {
            NSInteger count = 0;
            YY_FMResultSet *rsSecondSub = nil;

            rsSecondSub = [db executeQuery:@"select * from ChatMessage where contactId=?",last.ContactId];

            while ([rsSecondSub next]) {
                NSInteger isRead = [rsSecondSub intForColumn:@"isRead"];
                NSInteger isIncoming = [rsSecondSub intForColumn:@"isIncoming"];
                if (isIncoming == 1 && isRead == 0) {
                    count ++;
                }
            }
            last.unReadCount = count;
            [rsSecondSub close];
        }
        //end...
        
        last.ContactId = [Utility getBareContactId:[rs stringForColumn:@"contactId"]];
        
        [messageList addObject:last];
    }
    [rs close];
    return  messageList;
}

//获取与某个联系人聊天的未读消息个数
+ (NSInteger)fetchUnreadMsgCountToContactId:(NSString *)contactId
{
    NSInteger retVal = 0;
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"fetchUnreadMsgCountToContactId 数据打开失败");
        return 0;
    }
    
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *queryString=@"select count(*) from ChatMessage where contactId=? and isRead=0";
    YY_FMResultSet *rs=[db executeQuery:queryString,contactId];
    while ([rs next]) {
        int count= [rs intForColumnIndex:0];
        if (count!=0){
            retVal = count;
            break;
        }
        else
        {
            break;
        }
    }
    
    [rs close];
    return retVal;
}

//删除某条消息
+ (BOOL)deleteMessageId:(NSString *)messageId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return nil;
    };
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *deleteStr = [NSString stringWithFormat:@"DELETE FROM ChatMessage where messageId=?"];
    
    BOOL worked = [db executeUpdate:deleteStr, messageId];
    
    [db close];
    
    return worked;
}

//设置为已读状态
+ (BOOL)setTheMessageIsReaded:(NSString *)messageId
{
    //return [self saveUpdateMessageId:messageId fieldName:@"isRead" value:@"1"];
    return [self saveUpdateMessageId:messageId fieldName:@"isRead" valueInt:1];
}

//设置消息发送状态。服务器收到，对方收到
+ (BOOL)setTheMessageIsSendSuccess:(NSString *)messageId withSendStatus:(NSString *)isSendSuccess
{
    return [self saveUpdateMessageId:messageId fieldName:@"messageStatus" value:isSendSuccess];
}

//获取得到所有未读消息列表
+ (NSMutableArray *)getAllUnReadMessageList
{
    NSMutableArray *messageList=[[NSMutableArray alloc] init];
    
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据打开失败");
        return messageList;
    }
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *queryString=@"select * from ChatMessage where isRead=? order by createTime desc";
    YY_FMResultSet *rs=[db executeQuery:queryString,[NSNumber numberWithInt:0]];
    while ([rs next]) {
        //创建ChatMessage对象并保存到数据库表
        MessageBase *message = [[MessageBase alloc] init];
        message.messageId = [rs stringForColumn:@"messageId"];
        message.messageBody = [rs stringForColumn:@"messageBody"];
        message.messageType = (NSUInteger)[rs intForColumn:@"messageType"];
        message.createTime = [rs stringForColumn:@"createTime"];
        
        message.messageStatus = (ChatMsgState)[rs intForColumn:@"messageStatus"];
        message.isIncoming = (MsgIOStateType)[rs intForColumn:@"isIncoming"];
        message.contactId = [rs stringForColumn:@"contactId"];
        message.contactName = [rs stringForColumn:@"contactName"];
        message.isGroupMsg = [rs intForColumn:@"isGroupMsg"];
        
        message.isRead = [rs intForColumn:@"isRead"];
        message.duration = [rs intForColumn:@"duration"];
        message.content = [rs stringForColumn:@"content"];
        message.thumbnail = [rs stringForColumn:@"thumbnail"];
        
        message.localFileUrl = [rs stringForColumn:@"localFileUrl"];
        message.serverFileName = [rs stringForColumn:@"serverFileName"];
        
        message.fileSize = [rs intForColumn:@"fileSize"];
        message.fileName = [rs stringForColumn:@"fileName"];
        message.frommemberID = [rs stringForColumn:@"fromMemID"];

        id messageObj = [[UcfgroupXMPPManger sharedInstance] distributeMsgType:message.messageType message:message];
        
        GetChatMessage *dispathObj = [[GetChatMessage alloc] init];
        dispathObj.messageType = message.messageType;
        dispathObj.message = messageObj;
        
        [messageList addObject:messageObj];
    }
    
    [rs close];
    
    //
    //    for (int i= 0; i<[messageList count]; i++)
    //    {
    //        WXMessageObject *messageObj = [messageList objectAtIndex:i];
    //        //获取未读消息个数
    //        messageObj.messageNewCount = [self findUnreadMsgNumberby:messageObj.messageTo];
    //    }
    
    return  messageList;
}

//更新置顶NSInteger字段
+(BOOL)saveUpdateConnectId:(NSString*)connecTId fieldName:(NSString*)fieldName valueInt:(NSInteger)value
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    [self checkChatMessageTableCreatedInDb:db];
    
    NSString *updateStr = [NSString stringWithFormat:@"update ChatMessage set %@=? where contactId=?",fieldName];
    
    BOOL worked = [db executeUpdate:updateStr,[NSNumber numberWithInteger:value], connecTId];
    
    //FMDBQuickCheck(worked);
    
    [db close];
    
    return worked;
}


#pragma mark -----------------hanhan
//check ChatMessage table is create in db
+(BOOL)checkTableCreatedInDb:(YY_FMDatabase *)db
{
    BOOL worked = NO;
    NSString *createTable=@"CREATE  TABLE  IF NOT EXISTS TopConnectIdTab ('contactId' VARCHAR,'isTop' INT default 0)";
    worked = [db executeUpdate:createTable];
    if (!worked) {
        WXLog(@"Create ChatMessage'table resutl %d fail",worked);
    }
    
    FMDBQuickCheck(worked);
    return worked;
}
//查找messageId是否存在
+(BOOL)isFindTopConnectIdTabTheMessageIdExist:(NSString*)contactId
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return YES;
    };
    
    [self checkTableCreatedInDb:db];
    
    YY_FMResultSet *rs = [db executeQuery:@"select count(*) from TopConnectIdTab where contactId=?",contactId];
    
    while ([rs next]) {
        int count= [rs intForColumnIndex:0];
        
        if (count!=0){
            [rs close];
            return YES;
        }else
        {
            [rs close];
            return NO;
        }
    };
    [rs close];
    return YES;
}

//保存置顶信息 到TopConnectIdTab表
+(BOOL)saveTopConnectIdTabcontactId:(NSString *)contactId istop:(NSInteger )istop
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    [self checkTableCreatedInDb:db];
    
    //如果在表中已经存在，就更新此条消息的creatTime
    if([self isFindTopConnectIdTabTheMessageIdExist:contactId])
    {
        BOOL retb = [self updatecontactId:contactId istop:istop];
        return retb;
    }
    
    //否则插入此条消息
    NSString *insertStr = @"INSERT INTO TopConnectIdTab ('contactId','isTop') VALUES (?,?)";
    
    BOOL worked = [db executeUpdate:insertStr,contactId,
                   [NSNumber numberWithInteger:istop]];
    [db close];
    
    
    return worked;
}
//更新消息
+(BOOL)updatecontactId:(NSString*)messageId istop:(NSInteger )istop
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        WXLog(@"数据库打开失败");
        return NO;
    };
    [self checkTableCreatedInDb:db];
    
    NSString *updateStr = @"update TopConnectIdTab set isTop=? where contactId=?";
    
    BOOL worked = [db executeUpdate:updateStr,
                   [NSNumber numberWithInteger:istop],messageId];
    [db close];
    
    return worked;
}

+ (BOOL)checkIsTopState:(NSString *)connectid
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据打开失败");
        return NO;
    }
    [self checkTableCreatedInDb:db];
    
    NSString *queryString = @"select isTop from TopConnectIdTab where contactId= ?";
    YY_FMResultSet *rs = rs = [db executeQuery:queryString,connectid];
    

    NSInteger istop = 0;
    while ([rs next]) {
       istop = [rs intForColumn:@"isTop"];
    }
    if (istop) {
        return YES;
    }else{
        return NO;
    }
    return  YES;
}

@end
